package com.cfushn.ddd.tools.other;

import java.lang.reflect.Constructor;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import lombok.SneakyThrows;
import org.springframework.beans.BeanUtils;
import org.springframework.util.ObjectUtils;

/**
 * 通用转换
 *
 * @author CFuShn 2022/10/27 17:39
 */
@SuppressWarnings("unused")
public class ConvertUtil {

    @SneakyThrows
    public static <Target> Target trans(Object obj, Class<Target> targetClass) {
        if (null == obj) {
            return null;
        }
        // 获取targetClass的无参构造方法
        Constructor<Target> constructor = targetClass.getConstructor();
        Target target = constructor.newInstance();
        BeanUtils.copyProperties(obj, target);
        return target;
    }

    @SneakyThrows
    public static <Target> List<Target> transList(List<?> objList, Class<Target> targetClass) {
        if (ObjectUtils.isEmpty(objList)) {
            return Collections.emptyList();
        }
        // 获取targetClass的无参构造方法
        Constructor<Target> constructor = targetClass.getConstructor();
        List<Target> targetList = new ArrayList<>();
        for (Object obj : objList) {
            Target target = constructor.newInstance();
            BeanUtils.copyProperties(obj, target);
            targetList.add(target);
        }
        return targetList;
    }

}

